<?php
	require("frmCookie.php");
	
	$iOpcion = $_GET[iOpcion];
	$iMensaje = $_GET[iMensaje];
	
	switch ($iMensaje)
	{
		case 1:
		{
			$mensaje = "Los Equipos fueron cerrados Exitosamente.";
			break;
		}
		case 2:
		{
			$mensaje = "No hay datos para los criterios solicitados.";
			break;
		}
	}
	
	switch($iOpcion)
	{
		case 2:
		{
			
			$ordenes = array();
			$cantOrdenes = 0;
			
			$mySQL = "SELECT * FROM ordenes WHERE nroRemitoReceptor='" . $_POST[txtRemito] . "'";
			$result = readSQL($mySQL);
			foreach($result as $value)
			{
				array_push($ordenes, $value['idOrden']);
				$cantOrdenes++;
				
				//Almacen Laboratorio BULK
				$sqlAlm = "SELECT idAlmacen FROM almacenes WHERE idSucursal='" . $_SESSION['idSucursal'] . "' AND nombre='Equipos Terminados BULK'";
				$resultAlm = readSQL($sqlAlm);
				foreach($resultAlm as $valueAlm)
				{
					$idAlmacen = $valueAlm[0];
				}
				
				//Estado de la orden son los que traen mas INGRESADO En TRUE
				$idEstado = $value['idEstado'];
				$sqlCod = "SELECT codigo, nombre FROM estados WHERE idEstado=" . $value['idEstado'];
				$resultCod = readSQL($sqlCod);
				foreach($resultCod as $valCod)
				{
					$estado = $valCod[0];
				}
				$sqlEst = "SELECT idEstado FROM estados WHERE codigo='" . $estado . "' AND terminado=1 AND entregado=1 AND comunicado=0 AND aceptado=0 AND rechazado=0 AND facturado=0 and procesado=0";
				$resultEst = readSQL($sqlEst);
				foreach($resultEst as $valueEst)
				{
					$idEstado = $valueEst[0];
				}
				
				// Fecha Hora Retiro Cliente
				$fecha = getdate();
				$dia = $fecha[mday];
				$mes = $fecha[mon];
				$ano = $fecha[year];
				$hora = $fecha[hours];
				$minutos = $fecha[minutes];
				$segundos = $fecha[deconds];
				$fechaHoraTotal =  $ano . "-" . $mes . "-" . $dia . " " . $hora . ":" . $minutos . ":" . $segundos;
				$mySQL = $mySQL . "'" . "$fechaHoraTotal', ";
				
				if($_POST[txtOpcion]==1)
				{
					$mySQL = "UPDATE ordenes SET activa=0, fechaHoraRetiroCliente='" . $fechaHoraTotal . "', observacionesRemitoReceptor = '" . $_POST[txtObservaciones] . "', nroRemitoReceptor = '" . $_POST[txtRemito] . "', idEstado = " . $idEstado . ", idAlmacen = " . $idAlmacen . " WHERE idOrden = " . $value['idOrden'];
					executeSQL($mySQL);
					
					$sqlEstado = "INSERT INTO estadosxorden SET idOrden=" . $value['idOrden'] . ", idEstado=" . $idEstado;
					executeSQL($sqlEstado);
				}
			}
			
			break;
		}
	}
?>
<html>
	<head>
    	<?php
		require("frmHeader.php");
		?>
        <style media="print">
		.esconder
		{
			display:none;	
		}
		</style>
		<script language="javascript" src="scripts/ajax.js"></script>
		<script language="javascript" src="scripts/validar.js"></script>
		<script language="javascript">
		
		var xmlHttp;
		var option = 0;
		
		function showIMEI(str)
			{
				xmlHttp = GetXmlHttpObject();
				if (xmlHttp == null)
	  			{
	  				alert ("Your browser does not support AJAX!");
	  				return;
	  			}
	  			 
				var url = "ajaxOrden.php";
				url = url + "?part=" + str;
				url = url + "&ver=" + document.frm.txtOpcion.value; //Si es 1 toco el boton Entregar, si es 2 toco el boton Ver
				url = url + "&op=23";
				url = url + "&q=" + frm.txtRemito.value;
				url = url + "&sid=" + Math.random();
				
				xmlHttp.onreadystatechange = stateChangedIMEI;
				xmlHttp.open("GET",url,true);
				xmlHttp.send(null);
			}
	
			function stateChangedIMEI() 
			{ 
				if (xmlHttp.readyState == 4)
				{ 
					document.getElementById("txtHint").innerHTML = xmlHttp.responseText;
					if(xmlHttp.responseText == "")
					{
						document.frm.submit();
					}
				}
			}
		
		function valida()
		{
			
			if(frm.txtRemito.value == "")
			{
				alert("Por favor ingrese el Nro.Remito.");
				frm.txtRemito.focus();
				return false;
			}
			if(frm.txtRemito.value == "0")
			{
				alert("El Nro.Remito tiene que ser distinto a 0.");
				frm.txtRemito.focus();
				return false;
			}
			
			showIMEI("");
			
			return false;
		}
						
		</script>
	</head>
	<body>
    	<table cellpadding="0" cellspacing="0" align="center" class="tablaPrincipal">
        	<tr>
            	<td align="center">
                	<?php
					require("frmSession.php"); 
					
					//Redirecciona a SINPERMISOS.PHP en caso de no tener permisos
					switch ($iOpcion)
					{
						case 1:
						case 2:
						{
							
							if (!(in_array(42001, $_SESSION[permisos])))
							{
							?>
							  <script language="JavaScript" type="text/javascript">
							  <!--
							  window.location.href = "sinPermisos.php"
							  //-->
							  </script>
							<?php
							}
							$titulo = "Entrega de Ordenes BULK";
							break;
						}
					}
					
					?>
                </td>
            </tr>
            <tr>
            	<td align="center">
                	<?php
					require("frmTitulo.php");
					?>
                </td>
            </tr>
            <?php 
            if($iOpcion != 2) 
        	{
            ?>
            <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <tr>
            	<td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="menuPrincipal">
                    	<tr>
                        	<td>
								<?php
                                require("frmMenu.php");
                                ?>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <tr>
                <td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="tituloPantalla">
                    	<tr>
                        	<td align="center">
                            	<p class="texto" align="left"><?php echo $titulo; ?></p>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
             <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <tr>
                <td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="estadoPantalla">
                    	<tr>
                        	<td align="center">
                            	<p class="texto" align="left"><?php echo $mensaje; ?></p>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
             <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <?php 
        	}
            ?>
            <tr>
                <td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="contenedorPrincipal">
                    	<tr>
                        	<td align="">
                        		<?php
                        		switch($iOpcion)
                        		{
                        			case 1:
                        			{
                				?>
                				<form name="frm" action="entregaBulk.php?iOpcion=2" method="post" onSubmit="return valida();">
		                			<table>
		                				<tr>
		                					<td>*Nro.Remito de Egreso:</td>
		                					<td><input type="text" name="txtRemito" size="20" maxlength="20" /></td>	<td colspan="2"><div id="txtHint"></div></td>
		                				</tr>
		                				<tr>
		                					<td colspan="2" align="center"><input type="button" name="cmdBuscar" value="Entregar" onClick="document.frm.txtOpcion.value=1;return valida();"><input type="button" name="cmdVer" value="Ver" onClick="document.frm.txtOpcion.value=2;return valida();">
		                				</tr>
		                			</table>
                                    <input type="hidden" name="txtOpcion" value="1">
        		            	</form>
        		            	<?php
                        				break;
                        			}
                        			case 2:
                        			{
                				?>
                					<table>
                						<?php
                						$mySQL = "SELECT * FROM sucursales WHERE idSucursal = " . $_SESSION['idSucursal'];
                						$result = readSQL($mySQL);
                						foreach($result as $value)
                						{
                							$nombre = $value['nombre'];
                							$direccion = $value['direccion'];
                							$cp = $value['cp'];
                							$telefono = $value['telefono'];
                						}
                						?>
                						<tr>
                							<td colspan="9"><b>Sucursal:</b> <?php echo $nombre; ?></td>
                						</tr>
                						<tr>
                							<td colspan="9"><b>Direccion:</b> <?php echo $direccion; ?>  -  <b>CP:</b> <?php echo $cp; ?></td>
                						</tr>
                						<tr>
                							<td colspan="9"><b>Telefono:</b> <?php echo $telefono; ?></td>
                						</tr>
                						<?php
                						$fecha = getdate();
										$dia = $fecha[mday];
										$mes = $fecha[mon];
										$ano = $fecha[year];
										$fecha =  $dia . "/" . $mes . "/" . $ano;
										
										$mySQLDatos = "SELECT C.nombre AS CLIENTE, R.nombre AS RECEPTORIA FROM ordenes O ";
										$mySQLDatos = $mySQLDatos . " LEFT JOIN clientes C ON C.idCliente = O.idCliente ";
										$mySQLDatos = $mySQLDatos . " LEFT JOIN receptorias R ON R.idReceptoria = O.idReceptoria ";
										$mySQLDatos = $mySQLDatos . " WHERE trim(O.nroRemitoReceptor)='" . $_POST[txtRemito] . "'";
										//echo $mySQLDatos;
										$result = readSQL($mySQLDatos);
                						foreach($result as $value)
                						{
                							$cliente = $value['CLIENTE'];
                							$receptoria = $value['RECEPTORIA'];
                						}
										$numeroDeRemitoEgreso = $_POST[txtRemito];
                						?>
                						<tr>
                							<td colspan="9"><b>Fecha:</b> <?php echo $fecha; ?></td>
                						</tr>
                						<tr>
                							<td colspan="9"><b>Cliente:</b> <?php echo $cliente; ?></td>
                						</tr>
                						<tr>
                							<td colspan="9"><b>Número de Remito de Egreso:</b> <?php echo $numeroDeRemitoEgreso; ?></td>
                						</tr>
                						<tr>
                							<td>&nbsp;</td>
                						</tr>
                						<tr>
                							<th class="listaHead">Marca</th>
                							<th class="listaHead">Modelo</th>
                							<th class="listaHead">Imei</th>
                                            <th class="listaHead">Imei Reemplazo</th>
                							<th class="listaHead">Reingreso</th>
                							<th class="listaHead">Garantia</th>
                							<th class="listaHead">M.Garantia</th>
                							<th class="listaHead">Observaciones</th>
                							<th class="listaHead">N.Precio</th>
                							<th class="listaHead">Estado</th>
                							<th class="listaHead">F.Ingreso</th>
                							<th class="listaHead">Nro.Orden</th>
                							<th class="listaHead">Nro.Remito Ingreso</th>
                							<th class="listaHead">Cod.Referencia</th>
                							<th class="listaHead">Sintoma</th>
                							<th class="listaHead">Falla</th>
                							<th class="listaHead">Accion</th>
                						</tr>
                						<?php
										$j = 1;
                						for($i = 0; $i < $cantOrdenes; $i++)
            							{
            								$mySQL = "SELECT O.*, MC.nombre AS MARCA, M.nombreComercial AS NOMBRECOMERCIAL, O.nombrePrecio AS PRECIO, E.nombre AS ESTADO, (SELECT MAX(idOrden) FROM ordenes O1 WHERE O1.idOrden <> " .  $ordenes[$i] . " AND O1.imei = O.imei) AS REINGRESO FROM ordenes O INNER JOIN estados E ON E.idEstado = O.idEstado INNER JOIN modelos M ON M.idModelo = O.idModelo INNER JOIN marcas MC ON MC.idMarca = M.idMarca WHERE O.idOrden = " . $ordenes[$i];
            								$result = readSQL($mySQL);
											
            								foreach($result as $value)
            								{
			        							if($j%2==0)
				        							$class = "par";
												else
													$class = "impar";
			        					?>
    									<tr>
    										<td class="<?php echo $class; ?>"><?php echo $value['MARCA']; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $value['NOMBRECOMERCIAL']; ?></td>
    										<td class="<?php echo $class; ?>" align="right"><?php echo $value['imei']; ?></td>
                                            <td class="<?php echo $class; ?>" align="right"><?php echo $value['imeiSalida']; ?></td>
    										<?php
    										if($value['REINGRESO'] == null)
    											$reingreso = "NO";
    										else
    											$reingreso = "SI";
    										?>
    										<td class="<?php echo $class; ?>"><?php echo $reingreso; ?></td>
    										<?php
    										if($value['garantia'] == 1)
    										{
    											$garantia = "SI";
    											if($value['mantieneGarantia'] == 1)
    												$mantiene = "SI";
    											else
    												$mantiene = "NO";
    										}
    										else
    										{
    											$garantia = "NO";
    											$mantiene = "--";
    										}
    										?>
    										<td class="<?php echo $class; ?>"><?php echo $garantia; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $mantiene; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $value['observaciones']; ?></td>
    										<td class="<?php echo $class; ?>" align="right"><?php echo $value['PRECIO']; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $value['ESTADO']; ?></td>
    										<?php
    										list($ano, $mes, $dia) =  split("-", substr($value['fechaHoraInicio'], 0, 10));
											$fechaIngreso = $dia . "/" . $mes . "/" . $ano;
    										?>
    										<td class="<?php echo $class; ?>"><?php echo $fechaIngreso; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $value['idOrden']; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $value['nroRemitoEmisor']; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $value['codigoReferencia']; ?></td>
    										<?php
    										$mySQL = "SELECT S.nombre AS SINTOMA, F.nombre AS FALLA, A.nombre AS ACCION ";
    										$mySQL = $mySQL . " FROM reparaciones R, sintomas S, fallas F, acciones A ";
    										$mySQL = $mySQL . " WHERE R.idSintoma = S.idSintoma ";
    										$mySQL = $mySQL . " AND R.idFalla = F.idFalla ";
    										$mySQL = $mySQL . " AND R.idAccion = A.idAccion ";
    										$mySQL = $mySQL . " AND R.idOrden = " . $value['idOrden'];
    										$result = readSQL($mySQL);
            								foreach($result as $valueReparacion)
            								{
            									$sintoma = $valueReparacion['SINTOMA'];
            									$falla = $valueReparacion['FALLA'];
            									$accion = $valueReparacion['ACCION'];
            								}
    										?>
    										<td class="<?php echo $class; ?>"><?php echo $sintoma; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $falla; ?></td>
    										<td class="<?php echo $class; ?>"><?php echo $accion; ?></td>
    									</tr>
    									<?php
												$j++;
            								}
            							}
                						?>
                						<tr>
                                        <td colspan="16">&nbsp;
                                        	
                                        </td>                              
                                        </tr>
                                        <tr>
                							<td colspan="16" align="center"><input type="button" name="cmdImprimir" value="Imprimir" class="esconder" onClick="javascript: window.print();" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" name="cmdCerrar" value="Cerrar" class="esconder" onClick="javascript: window.location.href = 'main.php'" /></td>
                						</tr>
                					</table>
                				<?php
                        				break;
                        			}
                        		}
                        		?>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
	</body>
</html>